package com.lzc.demowar;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class DemoController {

    @ResponseBody
    @GetMapping("/demo")
    public Object demo(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "请求成功");
        map.put("data1", request.getServletContext().getRealPath("images/"));
        map.put("data2", request.getSession().getServletContext().getRealPath("images"));
        return map;
    }

    @GetMapping("/index")
    public ModelAndView index() {
        return new ModelAndView("index");
    }

    @PostMapping("/upload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file,
                         HttpServletRequest request) {

        try {
            Thumbnails.of(file.getInputStream()).forceSize(300, 800).outputQuality(1.0f).toFile("D:\\" + file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
        }

//        String contentType = file.getContentType();
//        String fileName = file.getOriginalFilename();
//        String filePath = request.getSession().getServletContext().getRealPath("WEB-INF/classes/static/images/");
//
//        System.out.println("fileName-->" + fileName);
//        System.out.println("getContentType-->" + contentType);
//        System.out.println("filePath-->" + filePath);
//
//        try {
//            uploadFile(file.getBytes(), filePath, System.currentTimeMillis()+".jpg");
//        } catch (Exception e) {
//            // TODO: handle exception
//        }

        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "上传成功");
        map.put("data", "data");
        return map;
    }

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

}
